package com.weixx.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Auther weixx
 * @Date 2022/2/25
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //所有的中间件技术都是基于 tcp/ip 协议 ，只不过rabbitMQ遵循的是amqp
        //tcp/ip肯定躲不过ip port
        //1.创建连接工程
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("47.101.36.174");
        cf.setPort(5672);
        cf.setUsername("admin");
        cf.setPassword("admin");
        cf.setVirtualHost("/");
        //2.创建连接Connection
        Connection connection=cf.newConnection("生产者");
        //3.通过连接获取通道Channel
        Channel channel = connection.createChannel();
        //4.通过创建交换机，声明队列，绑定关系，路由key，发送消息和接收消息
        channel.basicConsume("qunue1", true, new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                System.out.println("收到消息是" + new String(delivery.getBody(), "UTF-8"));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {
                System.out.println("接收失败了...");
            }
        });
        System.out.println("开始接收消息");
        System.in.read();//阻断一下
        //7.关闭连接
        if (channel!=null && channel.isOpen()){
            channel.close();
        }
        //8.关闭通道
        if (connection!=null&&connection.isOpen()){
            connection.close();
        }
    }
}
